package com.usian.admin.gateway.filters;

import com.usian.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthorizeFilters implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request，response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断请求路径是否为   /login/in
        if(request.getURI().getPath().contains("/login/in")){
            //放行
            return chain.filter(exchange);
        }
        //获取请求头信息中的token
        String token = request.getHeaders().getFirst("token");
        //校验token是否存在
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            //解析token中的内容
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //校验claimsBody的内容
            int i = AppJwtUtil.verifyToken(claimsBody);
            //说明token在有效期内
            if(i==-1||i==0){
                //合法，则向header中重新设置userId
                Integer id = (Integer) claimsBody.get("id");
                log.info("find userId:{} from url:{}",id,request.getURI());
                //重新设置token到header中
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("userId",id+"");
                }).build();
                //重新构建请求头信息
                exchange.mutate().request(serverHttpRequest).build();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            //想客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //放行
        return chain.filter(exchange);
    }
    //获取order值的方法
    @Override
    public int getOrder() {
        return 0;
    }
}
